package com.ruoyi.print.controller;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.print.domain.PrintFileUpload;
import com.ruoyi.print.service.IPrintFileUploadService;

import java.util.ArrayList;

/**
 * 打印文件上传Controller
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/print/file")
public class PrintFileUploadController extends BaseController
{
    @Autowired
    private IPrintFileUploadService printFileUploadService;

    /**
     * 查询打印文件上传列表
     */
    @PreAuthorize("@ss.hasPermi('print:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(PrintFileUpload printFileUpload)
    {
        startPage();
        List<PrintFileUpload> list = printFileUploadService.selectPrintFileUploadList(printFileUpload);
        return getDataTable(list);
    }

    /**
     * 导出打印文件上传列表
     */
    @PreAuthorize("@ss.hasPermi('print:file:export')")
    @Log(title = "打印文件上传", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PrintFileUpload printFileUpload)
    {
        List<PrintFileUpload> list = printFileUploadService.selectPrintFileUploadList(printFileUpload);
        ExcelUtil<PrintFileUpload> util = new ExcelUtil<PrintFileUpload>(PrintFileUpload.class);
        return util.exportExcel(list, "打印文件上传数据");
    }

    /**
     * 获取打印文件上传详细信息
     */
    @PreAuthorize("@ss.hasPermi('print:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(printFileUploadService.selectPrintFileUploadById(id));
    }

    /**
     * 新增打印文件上传
     */
    @PreAuthorize("@ss.hasPermi('print:file:add')")
    @Log(title = "打印文件上传", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PrintFileUpload printFileUpload)
    {
        return toAjax(printFileUploadService.insertPrintFileUpload(printFileUpload));
    }

    /**
     * 修改打印文件上传
     */
    @PreAuthorize("@ss.hasPermi('print:file:edit')")
    @Log(title = "打印文件上传", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PrintFileUpload printFileUpload)
    {
        return toAjax(printFileUploadService.updatePrintFileUpload(printFileUpload));
    }

    /**
     * 删除打印文件上传
     */
    @PreAuthorize("@ss.hasPermi('print:file:remove')")
    @Log(title = "打印文件上传", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(printFileUploadService.deletePrintFileUploadByIds(ids));
    }

    /**
     * 上传打印文件
     */
    @PreAuthorize("@ss.hasPermi('print:file:upload')")
    @Log(title = "打印文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file)
    {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件类型
            if (!printFileUploadService.validateFileType(file)) {
                return error("不支持的文件类型，请上传PDF、DOC、DOCX、TXT、JPG、PNG、BMP、TIFF格式的文件");
            }
            
            // 验证文件大小
            if (!printFileUploadService.validateFileSize(file)) {
                return error("文件大小不能超过50MB");
            }
            
            // 上传文件
            PrintFileUpload result = printFileUploadService.uploadPrintFile(file);
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", result.getId());
            data.put("fileName", result.getFileName());
            data.put("originalName", result.getOriginalName());
            data.put("fileUrl", result.getFileUrl());
            data.put("fileSize", result.getFileSize());
            data.put("fileType", result.getFileType());
            data.put("fileExtension", result.getFileExtension());
            data.put("message", "上传成功");
            
            return success(data);
            
        } catch (Exception e) {
            logger.error("打印文件上传失败", e);
            return error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 批量上传打印文件
     */
    @PreAuthorize("@ss.hasPermi('print:file:upload')")
    @Log(title = "批量打印文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/batch-upload")
    public AjaxResult batchUploadFiles(@RequestParam("files") List<MultipartFile> files)
    {
        try {
            if (files == null || files.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件数量
            if (files.size() > 10) {
                return error("一次最多只能上传10个文件");
            }
            
            // 批量上传
            List<PrintFileUpload> results = printFileUploadService.batchUploadPrintFiles(files);
            
            // 转换为前端期望的数据格式
            List<Map<String, Object>> formattedResults = new ArrayList<>();
            for (PrintFileUpload result : results) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", result.getId());
                item.put("fileName", result.getFileName());
                item.put("originalName", result.getOriginalName());
                item.put("fileUrl", result.getFileUrl());
                item.put("fileSize", result.getFileSize());
                item.put("fileType", result.getFileType());
                item.put("fileExtension", result.getFileExtension());
                item.put("remark", result.getRemark());
                formattedResults.add(item);
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("results", formattedResults);
            data.put("total", formattedResults.size());
            data.put("message", "批量上传完成");
            
            return success(data);
            
        } catch (Exception e) {
            logger.error("批量打印文件上传失败", e);
            return error("批量上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除OSS文件
     */
    @PreAuthorize("@ss.hasPermi('print:file:delete')")
    @Log(title = "删除打印文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete-oss")
    public AjaxResult deleteOssFile(@RequestParam("url") String url)
    {
        try {
            // 这里需要调用OSS服务删除文件
            // boolean success = ossService.deleteFile(url);
            // if (success) {
            //     return success("删除成功");
            // } else {
            //     return error("删除失败");
            // }
            return success("删除功能待实现");
        } catch (Exception e) {
            logger.error("删除OSS文件失败", e);
            return error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取支持的文件类型
     */
    @GetMapping("/supported-types")
    public AjaxResult getSupportedTypes()
    {
        Map<String, Object> data = new HashMap<>();
        data.put("document", new String[]{"pdf", "doc", "docx", "txt"});
        data.put("image", new String[]{"jpg", "jpeg", "png", "bmp", "tiff"});
        data.put("maxSize", "50MB");
        return success(data);
    }
} 